/*
 * @Author jiangzhiwei
 * @Date 2023-07-21 18:27:45
 * @LastEditors jiangzhiwei
 * @LastEditTime 2023-07-29 21:48:20
 * @FilePath \test-cron\src\components\yc-cron\components\panes\show-pane\index.js
 * @Description 显示面板
 */
import { defineComponent } from 'vue-demi'
import { h } from '../../../utils/domutil'
import { emitValue } from '../../../utils/componentutil'
import { DEFAULT_EXPRESSION_CATEGORY_NAMES, getOptionDuration } from '../../../utils/config'
import { LINUX_TYPE, TAB_EMIT_NAME, VALUE_EMIT_NAME, VALUE_NAME } from '../../../utils/constant'
import { validateExpression, getNextActionTimeList } from '../../../utils/parse'
import CommonInputNumber from '../../base/common-input-number'
import './showpane.css'

const NAME = 'yc-cron-show-pane'

export default defineComponent({
  name: NAME,
  props: {
    /** linux/spring/quarts */
    type: {
      type: String,
      default: undefined
    },
    expression: {
      type: String,
      default: ''
    },
    /** 激活的标签项 */
    activeTab: {
      type: [String, Number, Boolean],
      default: undefined
    }
  },
  data () {
    return {
      defaultText: '_',
      /** 次数 */
      n: 5,
      /** 最近n次执行时间 */
      list: [],
      interval: undefined
    }
  },
  computed: {
    expressionList () {
      const expressionList = this.expression.split(' ')
      if (this.type === LINUX_TYPE) { // linux没有秒，需要补上
        expressionList.unshift('0')
      }
      return expressionList
    },
    /** 表达式拆分后的信息 */
    infos () {
      return [
        { index: 0, title: '秒', value: this.expressionList[0] || this.defaultText },
        { index: 1, title: '分', value: this.expressionList[1] || this.defaultText },
        { index: 2, title: '时', value: this.expressionList[2] || this.defaultText },
        { index: 3, title: '日', value: this.expressionList[3] || this.defaultText },
        { index: 4, title: '月', value: this.expressionList[4] || this.defaultText },
        { index: 5, title: '周', value: this.expressionList[5] || this.defaultText },
        { index: 6, title: '年', value: this.expressionList[6] }
      ]
    },
    result () {
      return this.infos.map(item => item.value)
    },
    /** 显示的表达式 */
    showInfos () {
      const duration = getOptionDuration(this.type)
      return this.infos.slice(duration[0], duration[1])
    },
    /** 表达式校验信息 */
    validateInfo () {
      return validateExpression(this.expression, this.type)
    },
    /** 错误信息 */
    errorMessage () {
      if (this.validateInfo.valid) {
        return ''
      } else {
        let message = this.validateInfo.message
        const index = this.validateInfo.index
        if (index !== -1) {
          message = `【${ DEFAULT_EXPRESSION_CATEGORY_NAMES[index] }】: ` + message
        }
        return `（${ message }）`
      }
    }
  },
  mounted () {
    this.updateList()
    this.interval = window.setInterval(this.updateList, 1000)
  },
  unmounted () {
    if (this.interval) {
      window.clearInterval(this.interval)
    }
  },
  methods: {
    onInput (e) {
      emitValue(this, e.target.value)
    },
    /** 执行时间的显示次数修改 */
    onUpdateN (value) {
      this.n = value
      this.updateList()
    },
    /** 显示面板中的表达式被点击 */
    onExpItemClick (value) {
      emitValue(this, value, TAB_EMIT_NAME)
    },
    /** 更新执行时间 */
    updateList () {
      const list = this.validateInfo.valid ? getNextActionTimeList(this.result, this.type, this.n) : []
      if (list.join() !== this.list.join()) {
        this.list = list
      }
    }
  },
  render () {
    return h(
      'article',
      { class: `${NAME}` },
      [
        h(
          'header',
          { class: `${NAME}__header` },
          `表达式${ this.errorMessage }`
        ),
        h(
          'div',
          { class: `${NAME}__body` },
          [
            h(
              'p',
              this.showInfos.reduce((arr, item, index) => {
                const span = h(
                  'span',
                  {
                    class: {
                      [`${NAME}__exp-item`]: true,
                      'is-active': this.activeTab === item.title,
                      'is-error': this.validateInfo.index === item.index
                    },
                    on: { click: () => this.onExpItemClick(item.title) }
                  },
                  item.value
                )
                arr.push(span)
                if (index !== this.showInfos.length - 1) { // 不是最后一项
                  arr.push(' ')
                }
                return arr
              }, [])
            ),
            h(
              'p',
              [
                h(
                  'span',
                  `最近 `
                ),
                h(
                  CommonInputNumber,
                  {
                    props: {
                      [VALUE_NAME]: this.n,
                      min: 1,
                      max: 100,
                      controlsPosition: 'right',
                      size: 'small'
                    },
                    on: { [VALUE_EMIT_NAME]: value => this.onUpdateN(value) }
                  }
                ),
                h(
                  'span',
                  ` 次执行时间`
                )
              ]
            )
          ],
          h(
            'ul',
            this.list.map(item => {
              return h(
                'li',
                item
              )
            })
          )
        )
      ]
    )
  }
})
